#!/bin/sh

# FILE=/opt/oracle/oradata/dbconfig/XE/sqlnet.ora
# until test -e "$FILE" ; do
#     echo "$FILE does not exist."
#     sleep 1s
# done

sed -i '$a DISABLE_OOB=ON' /opt/oracle/oradata/dbconfig/XE/sqlnet.ora

sqlplus -s / as sysdba <<EOF
    -- Create the datakit user. Replace the password placeholder with a secure password.
    CREATE USER datakit IDENTIFIED BY 123456;

    -- Grant access to the datakit user.
    GRANT CONNECT, CREATE SESSION TO datakit;
    GRANT SELECT_CATALOG_ROLE to datakit;
    GRANT SELECT ON DBA_TABLESPACE_USAGE_METRICS TO datakit;
    GRANT SELECT ON DBA_TABLESPACES TO datakit;
    GRANT SELECT ON DBA_USERS TO datakit;
    GRANT SELECT ON SYS.DBA_DATA_FILES TO datakit;
    GRANT SELECT ON V_\$ACTIVE_SESSION_HISTORY TO datakit;
    GRANT SELECT ON V_\$ARCHIVE_DEST TO datakit;
    GRANT SELECT ON V_\$ASM_DISKGROUP TO datakit;
    GRANT SELECT ON V_\$DATABASE TO datakit;
    GRANT SELECT ON V_\$DATAFILE TO datakit;
    GRANT SELECT ON V_\$INSTANCE TO datakit;
    GRANT SELECT ON V_\$LOG TO datakit;
    GRANT SELECT ON V_\$OSSTAT TO datakit;
    GRANT SELECT ON V_\$PGASTAT TO datakit;
    GRANT SELECT ON V_\$PROCESS TO datakit;
    GRANT SELECT ON V_\$RECOVERY_FILE_DEST TO datakit;
    GRANT SELECT ON V_\$RESTORE_POINT TO datakit;
    GRANT SELECT ON V_\$SESSION TO datakit;
    GRANT SELECT ON V_\$SGASTAT TO datakit;
    GRANT SELECT ON V_\$SYSMETRIC TO datakit;
    GRANT SELECT ON V_\$SYSTEM_PARAMETER TO datakit;

    -- Initialize testing data.
    CREATE TABLE students  ( student_id number(10) NOT NULL,  student_name varchar2(40) NOT NULL,  student_age varchar2(10)  );
    INSERT INTO students  (student_id, student_name, student_age)  VALUES  (3, 'Happy', '11');
    exit;
EOF

echo ""
echo "#########################"
echo "CREATED datakit USER!"
echo "#########################"

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/tmp/myapp/instantclient
/tmp/myapp/oracle --log-level debug --host 0.0.0.0 --port 1521 --username datakit --password 123456 --interval $DATAKIT_INTERVAL --service-name $ORACLE_SID --datakit-http-host $DATAKIT_HOST --datakit-http-port $DATAKIT_PORT
